package com.mingte.manghe.controller;

import cn.hutool.core.date.DateException;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.mingte.manghe.common.ResponseResult;
import com.mingte.manghe.config.ThreadPoolConfig;
import com.mingte.manghe.entity.LaborInformationEntity;
import com.mingte.manghe.service.LaborInformationService;
import com.mingte.manghe.utils.*;
import io.micrometer.core.instrument.binder.BaseUnits;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Api(tags = {"execl"})
@RestController
@RequestMapping(value = "/api/v1/execl")
public class ExeclController extends BaseController{

    private final Logger logger = LoggerFactory.getLogger(ExeclController.class);

    @Autowired
    private LaborInformationService laborInformationService;

    @Autowired
    private ThreadPoolConfig threadPoolConfig;

    private static List<String> list = new ArrayList<>();

    @ApiOperation(value="读取execl表格过滤信息")
    @PostMapping(value = "/reader")
    public ResponseResult<List<String>> execlReader(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        logger.info("文件=》",file.getName());
        InputStream inputStream = null;
        long startMain = 0;
        long endMain = 0;
        try {
            inputStream = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            List<Sheet> sheets = reader.getSheets();
            startMain = System.currentTimeMillis();
            for (Sheet sheet:sheets) {
                List<LaborInformationEntity> laborInformationEntities = SheetUtils.sheetToMap(sheet, (keys, maps) -> {
                    LaborInformationEntity laborInformationEntity = new LaborInformationEntity();
                    LaborInformationEntity laborEntity = mapToObject(keys, maps, laborInformationEntity);
                    //System.out.println(laborEntity.getIdCard() + " : "+laborEntity.getName());
                    return laborEntity;
                });

                //并行保存数据
                TaskDisposeUtils.disposeTask(threadPoolConfig.getPool(),laborInformationEntities,(laborEntity)->{
                    //long start = System.currentTimeMillis();
                    if(StringUtils.isNotEmpty(laborEntity.getIdCard()) && StringUtils.isNotEmpty(laborEntity.getName())){
                        int save = laborInformationService.save(laborEntity);
                        if(save == 0){
                            String s = Base64Utils.decode(laborEntity.getIdCard()) + " : 失败";
                            list.add(s);
                            //System.out.println(s);

                        }
                    }
                    //long end = System.currentTimeMillis();
                    //System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " : 耗时"+(end-start) );
                });

                //单线程
                /*for (LaborInformationEntity laborEntity:laborInformationEntities) {
                    System.out.println(laborEntity.getIdCard() + " : "+laborEntity.getName());
                    if(StringUtils.isNotEmpty(laborEntity.getIdCard()) && StringUtils.isNotEmpty(laborEntity.getName())){
                        int save = laborInformationService.save(laborEntity);
                        System.out.println(laborEntity.getIdCard()+" : "+(save > 1 ? "成功" : "失败"));
                    }
                }*/
            }
            endMain = System.currentTimeMillis();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
        System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " : 最终总耗时"+(endMain-startMain) );
        list.add(" : 最终总耗时"+(endMain-startMain));
        return ResponseResult.success(list);
    }

    /**
     * map与对象转换
     * @param keys
     * @return
     */
    private LaborInformationEntity mapToObject(String[] keys,Map<String,Object> maps,LaborInformationEntity laborInformationEntity){
        if(null == keys) {
            return null;
        }
        for (int i = 0; i < keys.length; i++) {
            try{
                switch (keys[i]){
                    case "身份证号":
                        Object card = maps.get(keys[i]);
                        if(null != card && StringUtils.isNotEmpty(card.toString())){
                            String s = card.toString();
                            if(IdcardUtil.isValidCard(s)){
                                laborInformationEntity.setIdCard(Base64Utils.encode(s));
                                //获取性别
                                int gender = IdcardUtil.getGenderByIdCard(s);
                                laborInformationEntity.setGender(gender);
                            }
                        }
                        break;
                    case "工厂名称":
                        Object employer = maps.get(keys[i]);
                        if(null != employer && StringUtils.isNotEmpty(employer.toString())){
                            laborInformationEntity.setEmployer(StringUtils.subStringForLength(employer.toString(),24));}
                        break;
                    case "输送日期":
                        Object delivery = maps.get(keys[i]);
                        if(null != delivery && StringUtils.isNotEmpty(delivery.toString())){
                            String deliveryDate = delivery.toString();
                            String s1 = deliveryDate.replace(".0", "");
                            String s = DateTimeUtils.ExcelDoubleToDate(s1);
                            /*if(s.contains("/")){
                                s = s.replaceAll("/", "-");
                            }
                            if(s.contains(".")){
                                s = s.replaceAll(".", "-");
                            }*/
                            DateTime parse = DateUtil.parse(s, "yyyy-MM-dd");
                            laborInformationEntity.setDeliveryDate(parse);
                        }
                        break;
                    case "姓名":
                        Object name = maps.get(keys[i]);
                        if(null != name && StringUtils.isNotEmpty(name.toString())){
                            laborInformationEntity.setName(name.toString());}
                        break;
                    case "手机号":
                        Object mobile = maps.get(keys[i]);
                        if(null != mobile && StringUtils.isNotEmpty(mobile.toString())){
                            if(Validator.isMobile(mobile.toString())){
                                laborInformationEntity.setMobile(mobile.toString());
                            }
                        }
                        break;
                    case "返费价格":
                        Object rebate = maps.get(keys[i]);
                        if(null != rebate && StringUtils.isNotEmpty(rebate.toString())){
                            laborInformationEntity.setRebate(StringUtils.subStringForLength(rebate.toString(),60));}
                        break;
                    case "资源归属":
                        Object resourceAttribution = maps.get(keys[i]);
                        if(null != resourceAttribution && StringUtils.isNotEmpty(resourceAttribution.toString())){
                            laborInformationEntity.setResourceAttribution(StringUtils.subStringForLength(resourceAttribution.toString(),24));}
                        break;
                    case "备注":
                        Object remark = maps.get(keys[i]);
                        if(StringUtils.isNotEmpty(remark.toString())){
                            laborInformationEntity.setRemark(StringUtils.subStringForLength(remark.toString(),40));}
                        break;
                    case "住址":
                        Object address = maps.get(keys[i]);
                        if(null != address && StringUtils.isNotEmpty(address.toString())){
                            laborInformationEntity.setAddress(StringUtils.subStringForLength(address.toString(),99));}
                        break;
                    default:
                        break;
                }
            }catch (DateException e){
                list.add(e.getMessage());
                System.out.println(e.getMessage());
            }catch (NullPointerException nullPointerException){
                list.add(nullPointerException.getMessage());
                System.out.println(nullPointerException.getMessage());
            }
        }
        laborInformationEntity.setCreateBy("system");
        laborInformationEntity.setCreateTime(new Date());
        return laborInformationEntity;
    }

}
